class ApiClient {
  constructor(baseURL = 'http://localhost:3000/api') {
    this.baseURL = baseURL;
    this.token = localStorage.getItem('authToken');
  }

  // 设置认证令牌
  setToken(token) {
    this.token = token;
    if (token) {
      localStorage.setItem('authToken', token);
    } else {
      localStorage.removeItem('authToken');
    }
  }

  // 通用请求方法
  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    };

    // 添加认证令牌
    if (this.token) {
      config.headers.Authorization = `Bearer ${this.token}`;
    }

    try {
      const response = await fetch(url, config);
      
      // 检查网络连接错误
      if (!response) {
        throw new Error('网络连接失败，请检查后端服务器是否启动');
      }
      
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || `HTTP ${response.status}`);
      }

      return data;
    } catch (error) {
      console.error('API请求错误:', error);
      
      // 如果是网络错误，提供更友好的错误信息
      if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
        throw new Error('后端服务器未启动或网络连接失败，请启动后端服务器');
      }
      
      throw error;
    }
  }

  // GET请求
  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' });
  }

  // POST请求
  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
    });
  }

  // PUT请求
  async put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data)
    });
  }

  // DELETE请求
  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' });
  }

  // 文件上传
  async upload(endpoint, formData) {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      method: 'POST',
      body: formData
    };

    if (this.token) {
      config.headers = {
        Authorization: `Bearer ${this.token}`
      };
    }

    try {
      const response = await fetch(url, config);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || `HTTP ${response.status}`);
      }

      return data;
    } catch (error) {
      console.error('文件上传错误:', error);
      throw error;
    }
  }
}

// 认证相关API
class AuthAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async login(email, password) {
    const response = await this.client.post('/auth/login', { email, password });
    if (response.success) {
      this.client.setToken(response.data.token);
    }
    return response;
  }

  async register(userData) {
    const response = await this.client.post('/auth/register', userData);
    if (response.success) {
      this.client.setToken(response.data.token);
    }
    return response;
  }

  async getCurrentUser() {
    return this.client.get('/auth/me');
  }

  logout() {
    this.client.setToken(null);
  }
}

// 用户相关API
class UserAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getUsers(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/users?${query}`);
  }

  async getUserById(id) {
    return this.client.get(`/users/${id}`);
  }

  async updateUser(id, userData) {
    return this.client.put(`/users/${id}`, userData);
  }

  async deleteUser(id) {
    return this.client.delete(`/users/${id}`);
  }
}

// 产品相关API
class ProductAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getProducts(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/products?${query}`);
  }

  async getProductById(id) {
    return this.client.get(`/products/${id}`);
  }

  async createProduct(productData) {
    return this.client.post('/products', productData);
  }

  async updateProduct(id, productData) {
    return this.client.put(`/products/${id}`, productData);
  }

  async deleteProduct(id) {
    return this.client.delete(`/products/${id}`);
  }

  async searchProducts(query) {
    return this.client.get(`/products/search?q=${encodeURIComponent(query)}`);
  }
}

// 自行车产品相关API
class BikeProductAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getBikeProducts(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/bike-products?${query}`);
  }

  async getBikeProductById(id) {
    return this.client.get(`/bike-products/${id}`);
  }

  async getBikeProductReviews(id, params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/bike-products/${id}/reviews?${query}`);
  }

  async addBikeProductReview(id, reviewData) {
    return this.client.post(`/bike-products/${id}/reviews`, reviewData);
  }

  async getHotBikeProducts(limit = 10) {
    return this.client.get(`/bike-products/hot/list?limit=${limit}`);
  }

  async searchBikeProductsSuggestions(query, limit = 5) {
    return this.client.get(`/bike-products/search/suggest?q=${encodeURIComponent(query)}&limit=${limit}`);
  }

  async getBikeProductCategories() {
    return this.client.get('/bike-products/categories/list');
  }
}

// 订单相关API
class OrderAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getOrders(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/orders?${query}`);
  }

  async getOrderById(id) {
    return this.client.get(`/orders/${id}`);
  }

  async createOrder(orderData) {
    return this.client.post('/orders', orderData);
  }

  async updateOrder(id, orderData) {
    return this.client.put(`/orders/${id}`, orderData);
  }

  async cancelOrder(id) {
    return this.client.post(`/orders/${id}/cancel`);
  }
}

// 文章相关API
class ArticleAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getArticles(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/articles?${query}`);
  }

  async getArticleById(id) {
    return this.client.get(`/articles/${id}`);
  }

  async createArticle(articleData) {
    return this.client.post('/articles', articleData);
  }

  async updateArticle(id, articleData) {
    return this.client.put(`/articles/${id}`, articleData);
  }

  async deleteArticle(id) {
    return this.client.delete(`/articles/${id}`);
  }

  async publishArticle(id) {
    return this.client.post(`/articles/${id}/publish`);
  }
}

// 仪表盘相关API
class DashboardAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getStats() {
    return this.client.get('/dashboard/stats');
  }

  async getSalesTrend(period = 'week') {
    return this.client.get(`/dashboard/sales-trend?period=${period}`);
  }

  async getTopProducts(limit = 10) {
    return this.client.get(`/dashboard/top-products?limit=${limit}`);
  }

  async getRecentActivities(limit = 20) {
    return this.client.get(`/dashboard/recent-activities?limit=${limit}`);
  }
}

// 通知相关API
class NotificationAPI {
  constructor(apiClient) {
    this.client = apiClient;
  }

  async getNotifications(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.client.get(`/notifications?${query}`);
  }

  async markAsRead(id) {
    return this.client.post(`/notifications/${id}/read`);
  }

  async markAllAsRead() {
    return this.client.post('/notifications/mark-all-read');
  }

  async getUnreadCount() {
    return this.client.get('/notifications/unread-count');
  }
}

// 创建全局API实例
const apiClient = new ApiClient();
const authAPI = new AuthAPI(apiClient);
const userAPI = new UserAPI(apiClient);
const productAPI = new ProductAPI(apiClient);
const bikeProductAPI = new BikeProductAPI(apiClient);
const orderAPI = new OrderAPI(apiClient);
const articleAPI = new ArticleAPI(apiClient);
const dashboardAPI = new DashboardAPI(apiClient);
const notificationAPI = new NotificationAPI(apiClient);

// 导出所有API
window.API = {
  auth: authAPI,
  users: userAPI,
  products: productAPI,
  bikeProducts: bikeProductAPI,
  orders: orderAPI,
  articles: articleAPI,
  dashboard: dashboardAPI,
  notifications: notificationAPI,
  client: apiClient
};

// 自动设置令牌（如果存在）
const savedToken = localStorage.getItem('authToken');
if (savedToken) {
  apiClient.setToken(savedToken);
}

console.log('全栈Node.js API客户端已初始化');